package com.futures.investm.activity;


import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.futures.investm.R;
import com.aries.ui.view.title.TitleBarView;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;


import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.utils.ToastUtil;

public class RadioActivity extends BaseTitleActivity {
    @BindView(R.id.progress)
    ProgressBar progressBar;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    private MediaPlayer plMediaPlayer;

    private AVObject data;
    private Timer timer = new Timer();
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if (plMediaPlayer != null && plMediaPlayer.isPlaying()) {
                handler.sendEmptyMessage(0);
            }
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (plMediaPlayer != null) {
                progressBar.setProgress(plMediaPlayer.getCurrentPosition());
                tvStart.setText(generateTime(plMediaPlayer.getCurrentPosition()));
            }
        }
    };


    @Override
    public void setTitleBar(TitleBarView titleBar) {
        titleBar.setOnLeftTextClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }).setTitleMainText("第一财经");

    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_radio;
    }

    private String path;

    @Override
    public void initView(Bundle savedInstanceState) {
        AVQuery<AVObject> query = new AVQuery<>("Radio");
        query.setLimit(10);
        query.setSkip(0 * 10);
        query.orderByDescending("createdAt");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                // list 是一个 AVObject 的 List
                // list 指的就是所有包含当前 tag 的 TodoFolder
                if (e == null) {
                    if (list.size()>0){
                        path = list.get(0).getString("url");
                        initPlay(path);
                    }
                }

            }
        });



//        data = getIntent().getParcelableExtra("data");
//        if (data != null) {
//            path = data.getString("radioUrl");
//            initPlay(path);
//        }
    }


    private void initPlay(String path) {
        plMediaPlayer = MediaPlayer.create(this, Uri.parse(path));
        plMediaPlayer.start();
        plMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                tvTotal.setText(generateTime(mp.getDuration()));
                progressBar.setMax(mp.getDuration());
            }
        });
        plMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                progressBar.setSecondaryProgress(percent);
            }
        });
        plMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                ivPlay.setImageResource(R.mipmap.ic_play);
            }
        });
        plMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                ToastUtil.show("请稍后尝试");
                return false;
            }
        });
        timer.schedule(timerTask, 0, 1000);

    }

    @OnClick({R.id.iv_play})
    void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.iv_play:
                if (plMediaPlayer.isPlaying()) {
                    ivPlay.setImageResource(R.mipmap.ic_play);
                    plMediaPlayer.pause();
                } else {
                    ivPlay.setImageResource(R.mipmap.ic_stop);
                    plMediaPlayer.start();
                }
                break;
        }
    }


    @Override
    protected void onDestroy() {
        if (plMediaPlayer != null) {
            if (plMediaPlayer.isPlaying()) {
                plMediaPlayer.stop();
            }
            plMediaPlayer.release();
            plMediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        super.onDestroy();
    }

    public static String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes,
                seconds) : String.format("%02d:%02d", minutes, seconds);
    }
}
